/*
 * Copyright (c) 2025 李伟国
 * SQL-API is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY
 * KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
 * NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package com.moyu.sql.business.utils;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.List;


/**
 * 分页工具类
 */
@Slf4j
public class PageUtils {
    /**
     * 开始分页
     */
    public static void startPage(){
        // 获取当前请求信息
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes == null ? null : requestAttributes.getRequest();
        int size = 10;
        int current = 1;
        if (request != null) {
            String sizeStr = request.getParameter("size");
            String currentStr = request.getParameter("current");

            if(StringUtils.isNotBlank(sizeStr)){
                size = Integer.parseInt(sizeStr);
            }
            if(StringUtils.isNotBlank(currentStr)){
                current = Integer.parseInt(currentStr);
            }
        }
        PageHelper.startPage(current, size);
    }

    /**
     * 获取分页信息
     * @param page 待处理的分页对象
     * @return 分页信息
     * @param <T> 泛型
     */
    public static <T> PageInfo<T> getPageInfo(List<T> page){
        return new PageInfo<>(page);
    }
}
